import React, { useState, useRef, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { DictTypeAPI, DictDataAPI } from "@/api/dictionary";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { X, Save } from "lucide-react";
const AutoResizingTextarea = ({
  value,
  onChange,
  placeholder,
  disabled,
  rows = 3,
  ...props
}) => {
  const textareaRef = useRef(null);

  // 当内容变化时调整高度
  useEffect(() => {
    if (textareaRef.current) {
      // 重置高度以正确计算滚动高度
      textareaRef.current.style.height = "auto";
      // 设置新高度为内容高度或最小行数高度
      const scrollHeight = textareaRef.current.scrollHeight;
      const minHeight = rows * 24; // 假设每行大约24px
      textareaRef.current.style.height = `${Math.max(
        scrollHeight,
        minHeight
      )}px`;
    }
  }, [value, rows]);

  return (
    <textarea
      ref={textareaRef}
      value={value}
      onChange={onChange}
      placeholder={placeholder}
      rows={rows}
      disabled={disabled}
      style={{
        resize: "none", // 禁用手动调整大小
        overflow: "hidden", // 隐藏滚动条
      }}
      {...props}
    />
  );
};
// 添加日期格式转换工具函数
const formatDateForInput = (dateString) => {
  if (!dateString) return "";

  // 处理完整ISO格式（如2025-08-01T00:00:00.000+08:00）
  try {
    const date = new Date(dateString);

    // 获取年、月、日并补零
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
  } catch (error) {
    console.error("日期格式转换失败:", error);
    return "";
  }
};

export default function ProjectForm({ project, onSubmit, onCancel }) {
  const [voltageLevels, setVoltageLevels] = useState([]);
  const [isLoadingVoltage, setIsLoadingVoltage] = useState(true);
 
  // 加载电压等级数据（根据新接口格式调整）
  useEffect(() => {
    const loadVoltageLevels = async () => {
      try {
        setIsLoadingVoltage(true);

        // 1. 获取所有字典类型（包含电压等级）
        const typeResponse = await DictTypeAPI.getList();
        if (typeResponse.code !== 200 || !typeResponse?.rows?.length) {
          throw new Error("获取字典类型失败");
        }

        // 2. 从返回的rows中找到"电压等级"的字典类型
        const voltageType = typeResponse.rows.find(
          (item) => item.dictName === "电压等级"
        );

        if (!voltageType || !voltageType.dictType) {
          throw new Error("未找到电压等级的dictType");
        }

        // 3. 使用dictType获取具体的电压等级数据（关键修改点）
        const dataResponse = await DictDataAPI.getList({
          dictType: voltageType.dictType, // 这里使用dictType而不是dictId
        });

        if (dataResponse.code !== 200 || !dataResponse?.rows) {
          throw new Error("获取电压等级数据失败");
        }

        // 4. 格式化数据为Select组件所需格式，并按排序号排序
        const formattedLevels = dataResponse.rows
          .sort((a, b) => (a.dictSort || 0) - (b.dictSort || 0))
          .map((item) => ({
            value: item.dictValue,
            label: item.dictLabel,
          }));
        console.log(formattedLevels, "formattedLevels");

        setVoltageLevels(formattedLevels);
      } catch (error) {
        console.error("加载电压等级失败:", error);
        // 失败时使用默认值作为降级方案
        setVoltageLevels([
          { value: "110kV", label: "110kV" },
          { value: "220kV", label: "220kV" },
          { value: "330kV", label: "330kV" },
          { value: "500kV", label: "500kV" },
          { value: "750kV", label: "750kV" },
          { value: "1000kV", label: "1000kV" },
        ]);
      } finally {
        setIsLoadingVoltage(false);
      }
    };

    loadVoltageLevels();
  }, []);

   const [formData, setFormData] = useState(() => {
    if (project) {
      return {
        ...project,
        // 转换日期格式为yyyy-MM-dd
        plannedStartDate: formatDateForInput(project.plannedStartDate),
        plannedEndDate: formatDateForInput(project.plannedEndDate),
        // 确保编辑时有默认状态
        projectStatus: project.projectStatus || "notStarted",
      };
    }
    return {
      projectName: "",
      voltageLevel: "",
      startLocation: "",
      endLocation: "",
      totalLengthKm: "",
      constructionUnit: "",
      designUnit: "",
      supervisionUnit: "",
      projectManager: "",
      technicalLeader: "",
      plannedStartDate: "",
      plannedEndDate: "",
      projectStatus: "", // 初始为空，提交时会处理
      projectDescription: "",
    };
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleInputChange = (field, value) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    // 基本验证
    if (!formData.projectName || !formData.voltageLevel) {
      alert("请填写项目名称和电压等级");
      return;
    }

    setIsSubmitting(true);
    try {
      // 当项目状态未选择时，自动设置为"未开工"
      const status = formData.projectStatus || "notStarted";

      const data = {
        ...formData,
        projectStatus: status, // 确保状态有值
      };

      // 处理日期格式
      if (data.plannedStartDate)
        data.plannedStartDate = new Date(data.plannedStartDate).toISOString();
      if (data.plannedEndDate)
        data.plannedEndDate = new Date(data.plannedEndDate).toISOString();

      if (data.totalLengthKm) {
        data.totalLengthKm = parseFloat(data.totalLengthKm);
      }

      await onSubmit(data);
    } catch (error) {
      console.error("提交表单失败:", error);
      alert("保存失败: " + (error.message || "未知错误"));
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Card className="mb-6 shadow-lg border-0">
      <CardHeader className="bg-gradient-to-r from-blue-50 to-indigo-50 border-b">
        <CardTitle className="flex items-center justify-between">
          <span>{project ? "编辑项目" : "新建项目"}</span>
          <Button
            variant="ghost"
            size="icon"
            onClick={onCancel}
            disabled={isSubmitting}
          >
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>

      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 表单内容保持不变 */}
          <div className="grid grid-cols-1 md:grid-cols-1 gap-4">
            <div>
              <Label htmlFor="projectName">项目名称 *</Label>
              <Input
                id="projectName"
                value={formData.projectName}
                onChange={(e) =>
                  handleInputChange("projectName", e.target.value)
                }
                placeholder="输入项目名称"
                required
                disabled={isSubmitting}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="voltageLevel">电压等级 *</Label>
              <Select
                value={formData.voltageLevel}
                onValueChange={(value) =>
                  handleInputChange("voltageLevel", value)
                }
                disabled={isSubmitting || isLoadingVoltage}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择电压等级" />
                </SelectTrigger>
                <SelectContent>
                  {isLoadingVoltage ? (
                    <SelectItem value="null" disabled>
                      加载中...
                    </SelectItem>
                  ) : voltageLevels.length > 0 ? (
                    voltageLevels.map((level) => (
                      <SelectItem key={level.value} value={level.value}>
                        {level.label}
                      </SelectItem>
                    ))
                  ) : (
                    <SelectItem value="" disabled>
                      无数据
                    </SelectItem>
                  )}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="totalLengthKm">线路长度 (km)</Label>
              <Input
                id="totalLengthKm"
                type="number"
                step="0.1"
                value={formData.totalLengthKm}
                onChange={(e) =>
                  handleInputChange("totalLengthKm", e.target.value)
                }
                placeholder="输入线路长度"
                disabled={isSubmitting}
              />
            </div>
            <div>
              <Label htmlFor="startLocation">起点位置</Label>
              <Input
                id="startLocation"
                value={formData.startLocation}
                onChange={(e) =>
                  handleInputChange("startLocation", e.target.value)
                }
                placeholder="输入起点位置"
                disabled={isSubmitting}
              />
            </div>

            <div>
              <Label htmlFor="endLocation">终点位置</Label>
              <Input
                id="endLocation"
                value={formData.endLocation}
                onChange={(e) =>
                  handleInputChange("endLocation", e.target.value)
                }
                placeholder="输入终点位置"
                disabled={isSubmitting}
              />
            </div>
          </div>

          {/* Organizational Information */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="constructionUnit">施工单位</Label>
              <Input
                id="constructionUnit"
                value={formData.constructionUnit}
                onChange={(e) =>
                  handleInputChange("constructionUnit", e.target.value)
                }
                placeholder="输入施工单位"
                disabled={isSubmitting}
              />
            </div>

            <div>
              <Label htmlFor="designUnit">设计单位</Label>
              <Input
                id="designUnit"
                value={formData.designUnit}
                onChange={(e) =>
                  handleInputChange("designUnit", e.target.value)
                }
                placeholder="输入设计单位"
                disabled={isSubmitting}
              />
            </div>

            <div>
              <Label htmlFor="supervisionUnit">监理单位</Label>
              <Input
                id="supervisionUnit"
                value={formData.supervisionUnit}
                onChange={(e) =>
                  handleInputChange("supervisionUnit", e.target.value)
                }
                placeholder="输入监理单位"
                disabled={isSubmitting}
              />
            </div>

            <div>
              <Label htmlFor="projectStatus">项目状态</Label>
              <Select
                value={formData.projectStatus}
                onValueChange={(value) =>
                  handleInputChange("projectStatus", value)
                }
                disabled={isSubmitting}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择项目状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="notStarted">未开工</SelectItem>
                  <SelectItem value="inProgress">已开工</SelectItem>
                  <SelectItem value="completed">已完工</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 其他表单字段保持不变 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="projectManager">项目经理</Label>
              <Input
                id="projectManager"
                value={formData.projectManager}
                onChange={(e) =>
                  handleInputChange("projectManager", e.target.value)
                }
                placeholder="输入项目经理姓名"
                disabled={isSubmitting}
              />
            </div>

            <div>
              <Label htmlFor="technicalLeader">技术负责人</Label>
              <Input
                id="technicalLeader"
                value={formData.technicalLeader}
                onChange={(e) =>
                  handleInputChange("technicalLeader", e.target.value)
                }
                placeholder="输入技术负责人姓名"
                disabled={isSubmitting}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="plannedStartDate">计划开工日期</Label>
              <Input
                id="plannedStartDate"
                type="date"
                value={formData.plannedStartDate}
                onChange={(e) =>
                  handleInputChange("plannedStartDate", e.target.value)
                }
                disabled={isSubmitting}
              />
            </div>

            <div>
              <Label htmlFor="plannedEndDate">计划完工日期</Label>
              <Input
                id="plannedEndDate"
                type="date"
                value={formData.plannedEndDate}
                onChange={(e) =>
                  handleInputChange("plannedEndDate", e.target.value)
                }
                disabled={isSubmitting}
              />
            </div>
          </div>

          <div>
            <Label htmlFor="projectDescription">项目概况</Label>

            <AutoResizingTextarea
              id="projectDescription"
              value={formData.projectDescription}
              onChange={(e) =>
                handleInputChange("projectDescription", e.target.value)
              }
              placeholder="输入项目描述信息..."
              rows={3}
              disabled={isSubmitting}
              className="w-full px-3 py-2 border rounded-md"
            />
          </div>

          <div className="flex justify-end gap-3 pt-4">
            <Button
              type="button"
              variant="outline"
              onClick={onCancel}
              disabled={isSubmitting}
            >
              取消
            </Button>
            <Button
              type="submit"
              className="bg-blue-600 hover:bg-blue-700 flex items-center gap-2"
              disabled={isSubmitting}
            >
              {isSubmitting ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  保存中...
                </>
              ) : (
                <>
                  <Save className="w-4 h-4" />
                  {project ? "更新项目" : "创建项目"}
                </>
              )}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
